package com.sxhuayuan.parking.queue.rabbitmq.consumer;

import java.io.IOException;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.sxhuayuan.parking.compenent.RabbitMQConfig;
import com.sxhuayuan.parking.entity.ParkingIn;
import com.sxhuayuan.parking.exception.ParkException;
import com.sxhuayuan.parking.queue.QueueService;
import com.sxhuayuan.parking.queue.msg.QueueMsg;
import com.sxhuayuan.parking.service.MemberService;
import com.sxhuayuan.parking.service.ParkService;
import com.sxhuayuan.parking.service.ParkingInService;
import com.sxhuayuan.parking.service.ParkingLotService;
import com.sxhuayuan.parking.service.PartnerpayService;
import com.sxhuayuan.parking.service.PluginService;

@Component("parkInConsumer")
@RabbitListener(queues = RabbitMQConfig.QUEUE_PARK_IN)
public class ParkInConsumer {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	QueueService queueService;
	@Resource(name = "pluginServiceImpl")
	PluginService pluginService;
	@Resource(name = "parkingLotServiceImpl")
	ParkingLotService lotService;
	@Resource(name = "parkingInServiceImpl")
	ParkingInService inService;
	@Resource(name = "partnerpayServiceImpl")
	PartnerpayService partnerpayService;
	@Resource(name = "memberServiceImpl")
	MemberService memberService;
	@Autowired
	ParkService parkService;

	/**
	 * 处理消息
	 * 
	 * 微信需要先查询车牌和appid之间的授权关系，没错，每个服务商都需要用户授权一次才可以
	 * 
	 * 支付宝
	 * 
	 * @param msg
	 */
	@RabbitHandler
	private void handlerMsg(byte[] bytes, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) throws IOException {

		QueueMsg msg = JSON.parseObject(bytes, QueueMsg.class);

		ParkingIn in = inService.findByUniqueId(msg.getId());

		if (in == null) {
			log.error("[{}]未找到入场记录", msg.getId());
			channel.basicAck(tag, false);
			return;
		}

		try {
			in = parkService.partnerpayEnter(in);
		} catch (ParkException e1) {
		}
		channel.basicAck(tag, false);
	}

}
